package com.think.oauth.user.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.think.common.controller.BaseController;
import com.think.common.utils.Common;
import com.think.common.utils.ExcelParse;
import com.think.common.utils.annotation.OperateType;
import com.think.common.utils.annotation.SysLog;
import com.think.oauth.user.constant.ResultCode;
import com.think.oauth.user.dao.user.ExternDao;
import com.think.oauth.user.model.OauthClientDetails;
import com.think.oauth.user.model.Permission;
import com.think.oauth.user.model.Result;
import com.think.oauth.user.model.Role;
import com.think.oauth.user.model.RolePermission;
import com.think.oauth.user.model.User;
import com.think.oauth.user.model.UserOauth;
import com.think.oauth.user.model.UserRole;
import com.think.oauth.user.service.CustomClientDetailService;
import com.think.oauth.user.service.PermissionService;
import com.think.oauth.user.service.RecordService;
import com.think.oauth.user.service.RolePermissionService;
import com.think.oauth.user.service.RoleService;
import com.think.oauth.user.service.UserOauthService;
import com.think.oauth.user.service.UserRoleService;
import com.think.oauth.user.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.service.OAuth;
import springfox.documentation.spring.web.readers.parameter.ParameterTypeReader;

@Api(description = "管理员操作接口")
@RequestMapping("/v1/admin")
@RestController
//@CrossOrigin(allowCredentials = "false", allowedHeaders = "Authorization")
public class AdminController extends BaseController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private ExternDao externDao;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private RolePermissionService rolePermissionService;

	@Autowired
	private RecordService recordService;

	@Autowired
	private UserOauthService userOauthService;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private CustomClientDetailService clientDetailService;

	@ApiOperation(value = "创建新的用户信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "name", value = "用户名", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "phone", value = "手机号码", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "email", value = "用户邮箱", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "nickname", value = "用户邮箱", required = false, paramType = "form", dataType = "String"),

	})
	@SysLog(operModul = "用户管理", operType = OperateType.ADD, operDesc = "添加用户信息")
	@RequestMapping(value = "user", method = RequestMethod.POST)
	public Result createUser(@RequestParam("name") String name, @RequestParam(required = false) String phone,
			@RequestParam(required = false) String email,
			@RequestParam(required = false) String nickname,
			HttpServletRequest request, HttpServletResponse response) {
		User user = new User();
		user.setPhone(phone);
		user.setName(name);
		user.setNickname(name);
		if (nickname!=null) {
			user.setNickname(nickname);
		}
		UserOauth oauth = null;
		oauth =userOauthService.getUserOauth(name, Common.USER_USERNAME_LOGIN);
		if (oauth!=null) {
			return Result.success(userService.getValidUser(oauth.getUserId()));
		}
		oauth =userOauthService.getUserOauth(email, Common.USER_EMAIL_LOGIN);
		if (oauth!=null) {
			return Result.success(userService.getValidUser(oauth.getUserId()));
		}
		oauth =userOauthService.getUserOauth(phone, Common.USER_PHONE_LOGIN);
		if (oauth!=null) {
			return Result.success(userService.getValidUser(oauth.getUserId()));
		}
		List<UserOauth> list = new ArrayList<UserOauth>();
		
		

		Result result = Result.success();
		Integer userId = Common.GetCurrentAuthor().getUserId();
		user.setUpdator(userId);
		user.setCreator(userId);
		
		if(phone!=null) {
			UserOauth poauth = new UserOauth();
			poauth.setIdentifier(phone);
			poauth.setLoginType(Common.USER_PHONE_LOGIN);
			poauth.setUpdator(userId);
			poauth.setCreator(userId);
			list.add(poauth);
		}
		
		if(email != null) {
			UserOauth emailOauth = new UserOauth();
			emailOauth.setIdentifier(email);
			emailOauth.setLoginType(Common.USER_EMAIL_LOGIN);
			emailOauth.setCredential(passwordEncoder.encode("123456"));
			emailOauth.setUpdator(userId);
			emailOauth.setCreator(userId);
			list.add(emailOauth);

		}
		
		
		if(name != null) {
			UserOauth nameOauth = new UserOauth();
			nameOauth.setIdentifier(name);
			nameOauth.setLoginType(Common.USER_USERNAME_LOGIN);
			nameOauth.setCredential(passwordEncoder.encode("123456"));
			nameOauth.setUpdator(userId);
			nameOauth.setCreator(userId);
			list.add(nameOauth);

		}
		if(list.size() == 0) {
			return Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		}
		try {
			userService.insertUser(user,list);
			return Result.success(user);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		}

	}

	@ApiOperation(value = "获取权限信息", notes = "")
	@ApiImplicitParam(name = "id", value = "权限id", required = true, paramType = "path", dataType = "String")
	@RequestMapping(value = "permission/{id}", method = RequestMethod.GET)
	public Result getPermission(@PathVariable("id") Integer id, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		Permission permission = permissionService.getById(id);
		if (permission != null) {
			result.setData(permission);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}
	
	@ApiOperation(value = "修改权限信息状态", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam( name = "id", value = "权限id", required = true, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "state", value = "状态", required = true, paramType = "form", dataType = "int")
	})
	@RequestMapping(value = "permission/state", method = RequestMethod.POST)
	public Result changePermissionState(@RequestParam("id") int id, @RequestParam("state") Integer state,HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		Permission permission = permissionService.getById(id);
		if (permission != null) {
			permission.setState(state == 0? 0 : 1);
			if (permissionService.updateById(permission)) {
				result.setData(permission);
			} 
			else
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}

	@ApiOperation(value = "创建新的权限信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "name", value = "权限名称", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "desc", value = "权限描述", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "parent", value = "父权限", required = false, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "resDesc", value = "资源描述", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "resPath", value = "资源路径", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "resOrder", value = "资源排序", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "resType", value = "资源类型", required = true, paramType = "form", dataType = "int"),

	})
	@SysLog(operModul = "用户管理", operType = OperateType.ADD, operDesc = "创建新的权限信息")
	@RequestMapping(value = "permission", method = RequestMethod.POST)
	public Result createPermission(
			@RequestParam("name") String name, 
			@RequestParam("desc") String desc,
			@RequestParam(required = false,value = "parent") Integer parent, 
			@RequestParam(required = false,value = "resDesc") String resDesc,
			@RequestParam(required = false,value = "resPath") String resPath, 
			@RequestParam(required = false,value = "resOrder") Integer resOrder,
			@RequestParam("resType") Integer resType, HttpServletRequest request, HttpServletResponse response) {
		Permission permission = permissionService.getOne(new QueryWrapper<Permission>().eq("name", name).eq("delflag", 0));
		Result result = Result.success();
		if (!name.startsWith("ROLE_")) {
			return Result.failure(ResultCode.SPECIFIED_PERMISSION_NAME_INVALID);
		}
		if (permission != null) {
			result = Result.failure(ResultCode.DATA_ALREADY_EXISTED);
			result.setMsg("该权限名已经存在");
		}
		else {
			permission = new Permission();
			permission.setName(name);
			permission.setDescription(desc);
			permission.setParent(parent);
			permission.setResDesc(resDesc);
			permission.setResPath(resPath);
			permission.setResOrder(resOrder);
			permission.setResType(resType);
			permission.setClient(Common.GetClient());
			Integer userId = Common.GetCurrentAuthor().getUserId();
			permission.setUpdator(userId);
			permission.setCreator(userId);
			if (permissionService.save(permission)) {
				result = Result.success(permission);
			} else {
				result = Result.failure(ResultCode.RESULE_DATA_NONE);
			}
		}
		return result;
	}

	@ApiOperation(value = "删除权限信息", notes = "")
	@RequestMapping(value = "permission/{id}", method = RequestMethod.DELETE)
	public Result delPermission(@PathVariable("id") Integer id, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		
		Permission permission = permissionService.getById(id);

		if (permission == null) {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
			result.setMsg("权限没有找到");
		} else {
			permission.setDelflag(1);
			permission.setUpdator(Common.GetCurrentAuthor().getUserId());
			if (permissionService.updateById(permission)) {
			} else {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}

		return result;
	}

	@ApiOperation(value = "更新权限信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "permissionId", value = "权限id", required = true, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "name", value = "权限名称", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "desc", value = "权限描述", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "parent", value = "父权限", required = false, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "resDesc", value = "资源描述", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "resPath", value = "资源路径", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "resOrder", value = "资源排序", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "resType", value = "资源类型", required = false, paramType = "form", dataType = "int"),

	})
	@SysLog(operModul = "用户管理", operType = OperateType.Update, operDesc = "更新权限信息")
	@RequestMapping(value = "permission", method = RequestMethod.PUT)
	public Result updatePermission(
			@RequestParam("permissionId") Integer id, 
			@RequestParam(required = false,value = "name") String name,
			@RequestParam(required = false,value = "desc") String desc, 
			@RequestParam(required = false,value = "parent") Integer parent,
			@RequestParam(required = false,value = "resDesc") String resDesc,
			@RequestParam(required = false,value = "resPath") String resPath,
			@RequestParam(required = false,value = "resOrder") Integer resOrder, 
			@RequestParam(required = false,value = "resType") Integer resType,
			HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		Permission permission = permissionService.getById(id);
		if (!name.startsWith("ROLE_")) {
			return Result.failure(ResultCode.SPECIFIED_PERMISSION_NAME_INVALID);
		}
		if (permission == null) {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
			result.setMsg("权限没有找到");
		}
		Integer userId = Common.GetCurrentAuthor().getUserId();
		if (name != null)
			permission.setName(name);
		if (desc != null)
			permission.setDescription(desc);
		if (parent != null)
			permission.setParent(parent);
		if (resDesc != null)
			permission.setResDesc(resDesc);
		if (resPath != null)
			permission.setResPath(resPath);
		if (resOrder != null)
			permission.setResOrder(resOrder);
		if (resType != null)
			permission.setResType(resType);
		permission.setUpdator(userId);
		if (permissionService.updateById(permission)) {
			result = Result.success(permission);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}

	@ApiOperation(value = "获取角色信息", notes = "")
	@ApiImplicitParam(name = "id", value = "角色id", required = true, paramType = "path", dataType = "String")
	@RequestMapping(value = "role/{id}", method = RequestMethod.GET)
	public Result getRole(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		Role role = roleService.getById(id);
		if (role != null) {
			result.setData(role);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}
	
	@ApiOperation(value = "修改角色信息状态", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam( name = "id", value = "角色id", required = true, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "state", value = "状态", required = true, paramType = "form", dataType = "int")
	})
	@RequestMapping(value = "role/state", method = RequestMethod.POST)
	public Result changeRoleState(@RequestParam("id") int id, @RequestParam("state") Integer state,HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		Role role = roleService.getById(id);
		if (role != null) {
			role.setState(state == 0? 0 : 1);
			if (roleService.updateById(role)) {
				result.setData(role);
			} 
			else
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}

	@ApiOperation(value = "创建新的角色信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "name", value = "角色名称", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "desc", value = "角色描述", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "isDef", value = "是否为默认角色", required = false, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pers", value = "关联的权限id数组", required = false, paramType = "form", dataType = "array"),
	})
	@SysLog(operModul = "用户管理", operType = OperateType.ADD, operDesc = "创建新的角色信息")
	@RequestMapping(value = "role", method = RequestMethod.POST)
	public Result createRole(
			@RequestParam("name") String name,
			@RequestParam("desc") String desc,
			@RequestParam(required = false,value = "isDef") Integer isDef, 
			@RequestParam(required = false,value = "pers") Integer[] pers,HttpServletRequest request, HttpServletResponse response) {

		Role role = roleService.getOne(new QueryWrapper<Role>().eq("name", name));
		
		Result result = Result.success();
		if (role != null) {
			result = Result.failure(ResultCode.DATA_ALREADY_EXISTED);
			result.setMsg("该角色名已经存在");
		}
		else {
			if (pers != null) {
				for (Integer per : pers) {
					if (permissionService.getById(per) == null) {
						result = Result.failure(ResultCode.SYSTEM_INNER_ERROR,"id为" + per + "的权限不存在");
						return result;
					}
				}
			}
			
			role = new Role();
			role.setDescription(desc);
			role.setName(name);
			role.setClient(Common.GetClient());
			role.setIsDefault(isDef);
			Integer userId = Common.GetCurrentAuthor().getUserId();
			role.setCreator(userId);
			role.setUpdator(userId);
			
			try {
				roleService.SaveNewRole(role, pers);
				role.setPermissions(roleService.getRolePers(role.getRoleId()));
				result = Result.success(role);
			} catch (Exception e) {
				// TODO: handle exception
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}
		
		return result;
	}
	@Autowired
    PasswordEncoder passwordEncoder;
	@ApiOperation(value = "批量导入用户", notes = "")
	@ApiImplicitParam(name = "filename", value = "文件名", required = true, paramType = "form", dataType = "file")
	@SysLog(operModul = "用户管理", operType = OperateType.ADD, operDesc = "批量导入用户")
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result uploadFile(@RequestParam("filename") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		System.out.print("上传文件===" + "\n");

		Result result = null;
		Integer userId = Common.GetCurrentAuthor().getUserId();
		// 判断文件是否为空
		if (file.isEmpty()) {
			result = Result.failure(ResultCode.USER_DATA_FILE_EMPTY);
		} else {
			// 获取文件名
			String fileName = file.getOriginalFilename();
			ArrayList<Map<String, Object>> list = null;
			try {
				list = ExcelParse.ParseExcel(file.getInputStream(), fileName);
			} catch (Exception e) {
				// TODO: handle exception
				result = Result.failure(ResultCode.DATA_IS_WRONG,"excel 文件解析失败");
			}
			
			try {
				for (Map<String, Object> map : list) {
					
//					if (!map.containsKey("username") || !map.containsKey("phone")||!map.containsKey("email")) {
//						map.put("result", false);
//						continue;
//					}
//					if (userOauthService.checkUserExits(map.get("phone").toString(), Common.USER_PHONE_LOGIN)) {
//						map.put("result", false);
//						continue;
//					}
//					if (userOauthService.checkUserExits(map.get("email").toString(), Common.USER_EMAIL_LOGIN)) {
//						map.put("result", false);
//						continue;
//					}
					User user = new User();
					user.setName(map.get("username").toString());

					if (map.containsKey("nickname")) {
						user.setNickname(map.get("nickname").toString());
					} else {
						user.setNickname(map.get("username").toString());
					}
//					user.setPhone(map.get("phone").toString());
//					user.setEmail(map.get("email").toString());
					user.setUpdator(userId);
					user.setCreator(userId);
//					UserOauth oauth = new UserOauth();
//					oauth.setLoginType(Common.USER_PHONE_LOGIN);
//					oauth.setIdentifier(user.getPhone());
//					oauth.setUpdator(userId);
//					oauth.setCreator(userId);
//					
//					UserOauth emailOauth = new UserOauth();
//					emailOauth.setLoginType(Common.USER_EMAIL_LOGIN);
//					emailOauth.setIdentifier(user.getEmail());
//					emailOauth.setCredential(passwordEncoder.encode(user.getPhone().substring(user.getPhone().length() - 6)));
//					emailOauth.setUpdator(userId);
//					emailOauth.setCreator(userId);
					
					UserOauth usernameOauth = new UserOauth();
					usernameOauth.setLoginType(Common.USER_USERNAME_LOGIN);
					usernameOauth.setIdentifier(user.getName());
					usernameOauth.setCredential(passwordEncoder.encode("123456"));
					usernameOauth.setUpdator(userId);
					usernameOauth.setCreator(userId);
					userService.insertUser(user, Arrays.asList( usernameOauth));
					externDao.InsertStudentInfo(map.get("studentId").toString(),Integer.parseInt(map.get("classId").toString()), map.get("trueName").toString(), user.getId(), 26);
//					userService.insertUser(user, Arrays.asList( emailOauth, oauth,usernameOauth));
					map.put("result", true);
					map.put("userId", userId);
				}
				result = Result.success(list);
			} catch (Exception e) {
				
				result = Result.failure(ResultCode.DATA_IS_WRONG,e.getMessage());
			}
			

			

		}
		return result;
	}

	@ApiOperation(value = "删除角色信息", notes = "")
	@ApiImplicitParam(name = "id", value = "角色id", required = true, paramType = "path", dataType = "String")
	@SysLog(operModul = "用户管理", operType = OperateType.Update, operDesc = "删除角色信息")
	@RequestMapping(value = "role/{id}", method = RequestMethod.DELETE)
	public Result delRole(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		Role role = roleService.getById(id);

		if (role == null) {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
			result.setMsg("角色没有找到");
		} else {
			role.setDelflag(1);
			role.setUpdator(Common.GetCurrentAuthor().getUserId());
			if (roleService.updateById(role)) {
			} else {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}

		return result;
	}

	@ApiOperation(value = "更新角色信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "id", value = "角色id", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "name", value = "角色名称", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "desc", value = "角色描述", required = false, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "isDef", value = "是否为默认角色", required = false, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pers", value = "关联的权限id数组", required = false, paramType = "form", dataType = "array"),
	})
	@SysLog(operModul = "用户管理", operType = OperateType.Update, operDesc = "更新角色信息")
	@RequestMapping(value = "role", method = RequestMethod.PUT)
	public Result updateRole(
			@RequestParam("id") Integer id, 
			@RequestParam(required = false,value = "name") String name,
			@RequestParam(required = false,value = "desc") String desc, 
			@RequestParam(required = false,value = "pers") Integer[] pers,
			@RequestParam(required = false,value = "isDef") Integer isDef, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		Role role = roleService.getById(id);
		if (role == null) {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
			result.setMsg("角色没有找到");
		} else {
			//判断一下  要修改的权限是否真实存在
			for (Integer per : pers) {
				if (permissionService.getById(per) == null) {
					result = Result.failure(ResultCode.SYSTEM_INNER_ERROR,"id为" + per + "的权限不存在");
					return result;
				}
			}
			//判断一下要修改的角色名是否已经存在
			if (name != null && !name.equals(role.getName())) {
				Role  nrole = roleService.getOne(new QueryWrapper<Role>().eq("name", name).eq("delflag", 0));
				if (nrole != null) {
					result = Result.failure(ResultCode.DATA_ALREADY_EXISTED);
					result.setMsg("该角色名已经存在");
					return result;
				}
				role.setName(name);
			}				
			if (desc != null)
				role.setDescription(desc);
			if (isDef != null)
				role.setIsDefault(isDef);
			role.setUpdator(Common.GetCurrentAuthor().getUserId());
		}
		try {
			roleService.updateRole(role, pers);
			role.setPermissions(roleService.getRolePers(id));
			result = Result.success(role);
		} catch (Exception e) {
			// TODO: handle exception
			result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		}
		
		return result;
	}

	@ApiOperation(value = "获取用户信息", notes = "")
	@ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "String")
	@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
	public Result getUser(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		User user = userService.getById(id);
		if (user != null) {
			result.setData(user);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}
	
	@ApiOperation(value = "修改用户信息状态", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam( name = "id", value = "用户id", required = true, paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "state", value = "状态", required = true, paramType = "form", dataType = "int")
	})
	@RequestMapping(value = "user/state", method = RequestMethod.POST)
	public Result changeUserState(@RequestParam("id") int id, @RequestParam("state") Integer state,HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		User user = userService.getById(id);
		if (user != null) {
			user.setState(state == 0? 0 : 1);
			if (userService.updateById(user)) {
				result.setData(user);
			} 
			else
				result = Result.failure(ResultCode.USER_NOT_EXIST);
		} else {
			result = Result.failure(ResultCode.RESULE_DATA_NONE);
		}
		return result;
	}
	
	@ApiOperation(value = "删除用户信息", notes = "")
	@ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "String")
	@SysLog(operModul = "用户管理", operType = OperateType.Delete, operDesc = "删除用户信息")
	@RequestMapping(value = "user/del/{id}", method = RequestMethod.POST)
	public Result delUser(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		User user = userService.getById(id);

		if (user == null) {
			result = Result.failure(ResultCode.USER_NOT_EXIST);
			result.setMsg("用户没有找到");
		} else {
			user.setDelflag(1);
			user.setUpdator(Common.GetCurrentAuthor().getUserId());
			if (userService.updateById(user)) {
			} else {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}

		return result;
	}

	@ApiOperation(value = "更新用户信息", notes = "")
	@SysLog(operModul = "用户管理", operType = OperateType.Update, operDesc = "更新用户信息")
	@RequestMapping(value = "user", method = RequestMethod.PUT)
	public Result updateUser(@RequestParam("id")Integer id,@RequestParam(required = false,value = "avatar")String avatarUrl,@RequestParam(required = false,value = "nickname")String nickname,
			@RequestParam(required = false,value =  "roles")List<Integer> rolesList) {
		User user = userService.getById(id);
		if (user == null) {
			return Result.failure(ResultCode.USER_NOT_EXIST);
		}
		user.setAvatarUrl(avatarUrl);
		user.setNickname(nickname);
		user.setUpdator(Common.GetCurrentAuthor().getUserId());
		try {
			
			if (rolesList != null) {
				List<UserRole> entityList = new ArrayList<>();
				for (int i = 0; i < rolesList.size(); i++) {
					Integer array_element = rolesList.get(i);
					UserRole  role = new UserRole();
					role.setUserId(user.getId());
					role.setRoleId(array_element);
					entityList.add(role);
				}
				userService.updateUser(user, entityList);
			}
			else {
				userService.updateUser(user, null);
			}
			
			return Result.success(user);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		}
	}

	@ApiOperation(value = "获取用户列表信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "page", value = "当前压迫查询的页码", required = true, paramType = "path", dataType = "int"),
			@ApiImplicitParam(name = "count", value = "每一页的数量", required = true, paramType = "path", dataType = "int"),

	})
	@RequestMapping(value = "users/{page}/{count}", method = RequestMethod.GET)
	public Result getUserList(@PathVariable("page") Integer page, @PathVariable("count") Integer count,
			HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		if (page >= 0 && count > 0) {
			IPage<User> userPage = new Page<>(page, count);
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.select(User.class, info -> !info.getColumn().equals("created_time")
					&& !info.getColumn().equals("updated_time") && !info.getColumn().equals("delflag"));
			queryWrapper.ne("delflag", 1);
			result.setData(userService.page(userPage, queryWrapper));
		} else {
			result = Result.failure(ResultCode.PARAM_IS_INVALID);
		}

		return result;
	}

	@ApiOperation(value = "获取角色列表信息信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "page", value = "当前压迫查询的页码", required = true, paramType = "path", dataType = "int"),
			@ApiImplicitParam(name = "count", value = "每一页的数量", required = true, paramType = "path", dataType = "int"),

	})
	@RequestMapping(value = "roles/{page}/{count}", method = RequestMethod.GET)
	public void getRoleList(@PathVariable("page") Integer page, @PathVariable("count") Integer count,
			HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		if (page >= 0 && count > 0) {
			IPage<Role> rolerPage = new Page<>(page, count);
			QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
			queryWrapper.select(Role.class, info -> !info.getColumn().equals("created_time")
					&& !info.getColumn().equals("updated_time") && !info.getColumn().equals("del_flag"));
			queryWrapper.ne("delflag", 1).eq("client", Common.GetClient());
			result.setData(roleService.page(rolerPage, queryWrapper));
		} else {
			result = Result.failure(ResultCode.PARAM_IS_INVALID);
		}

		outputJson(result, request, response);
	}

	@ApiOperation(value = "获取权限列表信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "page", value = "当前压迫查询的页码", required = true, paramType = "path", dataType = "int"),
			@ApiImplicitParam(name = "count", value = "每一页的数量", required = true, paramType = "path", dataType = "int"),

	})
	@RequestMapping(value = "permissions/{page}/{count}", method = RequestMethod.GET)
	public void getPermissionList(@PathVariable("page") Integer page, @PathVariable("count") Integer count,
			HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		if (page >= 0 && count > 0) {
			IPage<Permission> perPage = new Page<>(page, count);
			QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
			queryWrapper.select(Permission.class, info -> !info.getColumn().equals("created_time")
					&& !info.getColumn().equals("updated_time") && !info.getColumn().equals("del_flag"));
			queryWrapper.ne("delflag", 1).eq("client", Common.GetClient());
			result.setData(permissionService.page(perPage, queryWrapper));
		} else {
			result = Result.failure(ResultCode.PARAM_IS_INVALID);
		}

		outputJson(result, request, response);
	}
	
	@RequestMapping(value = "permissionTree/{page}/{count}", method = RequestMethod.GET)
	public void getPermissionTreeList(@PathVariable("page") Integer page, @PathVariable("count") Integer count,
			HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		if (page >= 0 && count > 0) {
//			IPage<Permission> perPage = new Page<>(page, count);
//			QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
//			queryWrapper.select(Permission.class, info -> !info.getColumn().equals("created_time")
//					&& !info.getColumn().equals("updated_time") && !info.getColumn().equals("del_flag"));
//			queryWrapper.ne("delflag", 1);
//			result.setData(permissionService.page(perPage, queryWrapper));
			result.setData(permissionService.getPermissionTree(page,count,Common.GetClient()));
		} else {
			result = Result.failure(ResultCode.PARAM_IS_INVALID);
		}

		outputJson(result, request, response);
	}
	
	
	@ApiOperation(value = "搜索权限信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "key", value = "搜索关键字", required = true, paramType = "query", dataType = "string"),

	})
	@RequestMapping(value = "permissions/search", method = RequestMethod.GET)
	public void getPermissionList(@RequestParam("key") String key,HttpServletRequest request, HttpServletResponse response) {
		Result result = Result.success();
		QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("name", key);
		queryWrapper.ne("delflag", 1).eq("client", Common.GetClient());
		result.setData(permissionService.list(queryWrapper));
		outputJson(result, request, response);
	}

	@ApiOperation(value = "获取指定角色的权限信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "roleId", value = "当前要查询的角色id", required = true, paramType = "path", dataType = "int"),

	})
	@RequestMapping(value = "permissions/{roleId}", method = RequestMethod.GET)
	public Result getRolePermissionList(@PathVariable("roleId") Integer roleId, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		result.setData(permissionService.getBaseMapper().getRolePermissions(roleId));
		return result;
	}

	@ApiOperation(value = "获取指定用户的角色信息", notes = "")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "userId", value = "当前要查询的用户id", required = true, paramType = "path", dataType = "int"),

	})
	@RequestMapping(value = "roles/{userId}", method = RequestMethod.GET)
	public Result getUserRoleList(@PathVariable("userId") Integer userId, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = Result.success();
		result.setData(roleService.getBaseMapper().getUserRoles(userId,Common.GetClient()));
		return result;
	}

	@ApiOperation(value = "搜索用户信息", notes = "")
	@ApiImplicitParam(name = "key", value = "搜索的关键字", required = true, paramType = "query", dataType = "String")
	@RequestMapping(value = "/user/search", method = RequestMethod.GET)
	public Result searchUsersLike(@RequestParam("key") String key, HttpServletRequest request,
			HttpServletResponse response) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("name", key).or().like("nickname", key);
		queryWrapper.ne("delflag", 1);
		return Result.success(userService.list(queryWrapper));
	}

	@ApiOperation(value = "搜索角色信息", notes = "")
	@ApiImplicitParam(name = "key", value = "搜索的关键字", required = true, paramType = "query", dataType = "String")
	@RequestMapping(value = "/role/search", method = RequestMethod.GET)
	public Result searchRolesLike(@RequestParam("key") String key, HttpServletRequest request,
			HttpServletResponse response) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("name", key);
		queryWrapper.ne("delflag", 1).eq("client", Common.GetClient());
		return Result.success(roleService.list(queryWrapper));
	}

	@ApiOperation(value = "搜索权限信息", notes = "")
	@ApiImplicitParam(name = "key", value = "搜索的关键字", required = true, paramType = "query", dataType = "String")
	@RequestMapping(value = "/permission/search", method = RequestMethod.GET)
	public Result searchPermissionsLike(@RequestParam("key") String key, HttpServletRequest request,
			HttpServletResponse response) {
		QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("name", key);
		queryWrapper.ne("delflag", 1).eq("client", Common.GetClient());
		return Result.success(permissionService.list(queryWrapper));
	}
	
	@ApiOperation(value = "获取权限树信息", notes = "")
	@RequestMapping(value = "/permission/tree", method = RequestMethod.GET)
	public Result GetPermissionTree(HttpServletRequest request,
			HttpServletResponse response) {
		QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("delflag", 1);
		return Result.success(permissionService.list(queryWrapper));
	}
	
	@RequestMapping(value = "client/{page}/{count}", method = RequestMethod.GET)
	public Result GetClientList(@PathVariable("page") Integer page, @PathVariable("count") Integer count) {
		QueryWrapper<OauthClientDetails> queryWrapper = new QueryWrapper<>();
		IPage<OauthClientDetails> ipage = new Page<OauthClientDetails>(page, count);
		return Result.success(clientDetailService.page(ipage,queryWrapper));
	}
	
	@RequestMapping(value = "client", method = RequestMethod.POST)
	public Result CreateNewClient(@RequestParam("client")String client,@RequestParam("redirect")String redirect) {
		if (clientDetailService.getById(client)!=null) {
			return Result.failure(ResultCode.CLIENT_ALREADY_EXITS);
		}
		OauthClientDetails oauthClientDetails = new OauthClientDetails();
		oauthClientDetails.setClientId(client);
		oauthClientDetails.setResourceIds("default");
		oauthClientDetails.setAuthorities("default");
		oauthClientDetails.setWebServerRedirectUri(redirect);
		oauthClientDetails.setClientSecret(passwordEncoder.encode(UUID.randomUUID().toString()));
		oauthClientDetails.setScope("all");
		oauthClientDetails.setAuthorizedGrantTypes("password,wx_web_code,authorization_code,refresh_token,ilab,ilab_token");
		return Result.success(clientDetailService.save(oauthClientDetails));
	}
	
	@RequestMapping(value = "client/{client}", method = RequestMethod.POST)
	public Result GetClientSecret(@PathVariable("client")String client) {
		OauthClientDetails oauthClientDetails = clientDetailService.getById(client);
		if (oauthClientDetails==null) {
			return Result.failure(ResultCode.CLIENT_ALREADY_EXITS);
		}
		String pwd = UUID.randomUUID().toString();
		oauthClientDetails.setClientSecret(passwordEncoder.encode(pwd));
		clientDetailService.updateById(oauthClientDetails);
		return Result.success(pwd);
	}
}
